<?php

namespace App\Api\Auth\Controllers;

use App\Api\Auth\Requests\AuthSendSmsRequest;
use App\Api\Auth\Models\UsersOpenId;
use Auth;
use App;
use App\Api\Auth\Models\AppVersion;
use Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Api\Auth\Requests\AuthLoginRequest;
use App\Api\Signup\Models\Photographer;
use App\Api\Signup\Models\PhotographerGames;
use App\Api\Signup\Models\UserDetail;
use App\Api\Signup\Services\SignupService;
use Carbon\Carbon;

class AuthController extends Controller
{
    // app上线检测
    public function check(Request $request)
    {
        $params = $request->all();
        // 版本号
        // 验证是否上线
        $version = data_get($params, 'version', 0);
        $type = data_get($params, 'type', '');
        $type = strtolower($type);
        $app = AppVersion::where('version', $version)->where('type', $type)->select('status')->first();
        if (empty($app)) {
            $check = true;
        } else {
            $status = data_get($app, 'status', 0);
            if ($status == 1) {
                $check = true;
            } else {
                $check = false;
            }
        }

        return $this->formatOutput($check);
    }
    // app版本接口
    public function saveAppVersion(Request $request)
    {
        $params = $request->all();
        $version = data_get($params, 'version', 0);
        $type = data_get($params, 'type', '');
        $status = data_get($params, 'status', 1);
        $remarks = data_get($params, 'remarks', '');
        $type = strtolower($type);
        $app = AppVersion::where('version', $version)->where('type', $type)->first();

        $data['version'] = $version;
        $data['type'] = $type;
        $data['status'] = $status;
        if (empty($app)) {
            $data['remarks'] = $remarks;
            $check = AppVersion::create($data);
        } else {
            $remarks = data_get($app, 'remarks', '') . ';' . $remarks;
            $data['remarks'] = $remarks;
            $check = $app->update($data);
        }
        return $this->formatOutput($check);
    }
    /**
     * 登录
     * @param AuthLoginRequest $request
     * @return array
     */
    public function login(AuthLoginRequest $request)
    {
        $params = $request->all();

        $name = data_get($params, 'name', '');
//        $password = data_get($params, 'password', '');
        if (!is_numeric($name)) {
            $bUser = App\Api\Auth\Models\Users::where('login_name', '=', $name)
                ->first();
//            $name = data_get(User::find(data_get($bUser, 'user_id')), 'mobile', '');
        } else {
            $user = App\Api\Auth\Models\Users::where('mobile', '=', $name)
                ->first();
            $bUser['user_id'] = data_get($user, 'id');
        }
        if (\Auth::guard('business')->attempt(['id' => data_get($bUser, 'user_id'), 'password' => $params['password']], 1)) {
            $user = \Auth::guard('business')->user();
            $user->real_name = data_get($user, 'login_name', '');
            return $this->formatOutput($user);
        } else {
            throw new \LogicException('用户名或密码错误', 20);
        }
    }

    public function getMe()
    {
        $user = \Auth::user();
        $user->real_name = data_get($user, 'login_name', '');
        return $this->formatOutput($user);
    }

    public function webGetMe()
    {
        $user = \Auth::user();

        if (data_get($user, 'vip_expiration', '') >= Carbon::now()->toDateTimeString()) {
            $user->is_vip = 1;
        } else {
            $user->is_vip = 0;
        }
        $birth = data_get($user, 'birth', '');
        if ($birth == '1970-01-01') {
            $user->age = 0;
        } else {
            $user->age = getAgeByBirth($birth);
        }
        $user->photos = json_decode(data_get($user, 'photos', ''));

        return $this->formatOutput($user);
    }

    /**
     * 获取摄影师信息
     *
     */
    public function adminAuthMe(Request $request)
    {
        $user = \Auth::user();
        return $this->formatOutput($user);
    }

    public function loginByToken(Request $request)
    {
        $params = $request->all();
        Auth::logout();
        $token = data_get($params, 'api_token', '');
        $user = App\Api\Auth\Services\AuthService::authByToken($token);

        Auth::loginUsingId($user->id);

        return $this->formatOutput(['url' => env('APP_URL') . '/web/weibu']);
    }

    /**
//     * 获取当前用户
//     *
//     * @return user
//     */
//    public function getMeWechat(Request $request)
//    {
//        $params = $request->all();
//        info('open login', $params);
//        $unionid = data_get($params, 'unionid', '');
//        if (empty($unionid)) {
//            $user = Auth::user();
//            if (empty($user)) {
//                throw new \LogicException('请重新登录', 401);
//            }
//            return $this->formatOutput($user);
//        }
//        $user_id = UsersOpenId::where('unionid', $unionid)->value('user_id');
//
//        $mobile = '';
//        if ($user_id > 0) {
//            $mobile = User::where('id', $user_id)->value('mobile');
//        }
//
//        if (empty($mobile))
//            throw new \LogicException('请绑定手机号', 601);
//
//        return $this->formatOutput('success');
//    }

    public function logout(Request $request)
    {
        Auth::logout();
        $result = new \stdClass();

        return $this->formatOutput($result);
    }

    /**
     * Route::post('auth/sms_code', 'AuthController@sendSmsCode');
     * @param AuthSendSmsRequest $request
     * @return array
     */
    public function sendSmsCode(AuthSendSmsRequest $request)
    {
        $params        = $request->all();
        $smsCodeMobile = 'sms_code_' . $params['mobile'];

        $smsCode = rand(100000, 999999);
        //todo: 附加时间戳, 一定时间后失效
        \Cache::put($smsCodeMobile, $smsCode, 15);
        $smsCode = \Cache::get($smsCodeMobile);

        if (!App::environment('testing')) {
            Log::info('发送短信验证码', [$params['mobile'], $smsCode]);
            //            hbSend($params['mobile'], "您的验证码为{$smsCode}，切勿告诉别人哦！", 10);
            $result = \Top::aliSendSms($params['mobile'], $smsCode, 'code');
        } else {
            Log::info('[测试]发送短信验证码', [$params['mobile'], $smsCode]);
            $result = "ceshi";
        }

        return $this->formatOutput('success');
    }

    public function webOpenLogin(Request $request)
    {
        $params = $request->all();
        info('open login', $params);

        $token    = $params['token'];
        $appId    = $params['app_id'];
        $shareId = data_get($params, 'share_id', '');
        $photoUrl = '';
        $nickName = '';
        if ($appId == config('payment.sport.wechat.app_id')) {
            $wechat  = new App\Libs\Wechat\WechatService($appId, config('payment.sport.wechat.app_secret'));
            $content = $wechat->getOAuth($token);
            info('open login wechat content', [$content]);

            $openId  = data_get($content, 'openid', false);
            $accessToken = data_get($content, 'access_token', '');
            $name        = microtime(true) * 10000;
            if (data_get($params, 'scope') == 'userinfo') {
                $res      = $wechat->snsUserInfo($openId, $accessToken);
                $content  = json_decode($res, true);
                $photoUrl = data_get($content, 'headimgurl', '');
                $photoUrl = str_replace('/132', '/64', $photoUrl);
                $nickName = data_get($content, 'nickname', '');
                $name     = $nickName;
            }
        } elseif ($appId == config('payment.jueqiweilaixcx.wechat.app_id')) {
            $wechat  = new App\Libs\Wechat\WechatService($appId, config('payment.jueqiweilaixcx.wechat.app_secret'));
            $content = $wechat->xcxJsCode2Session($token);
            $openId  = data_get($content, 'openid', false);
            $name    = microtime(true) * 10000;
        } else {
            throw new \LogicException('请重新登录', 401);
        }

        if (!$openId) {
            throw new \LogicException('请重新登录', 200);
        }
        $user = $this->checkUser($appId, $openId, $content);
        $user_id = data_get($user, 'id', 0);
        if ($user_id > 0) {
            Auth::loginUsingId($user_id, true);
        }
        if (!empty($shareId)) {
            $user = User::find($user_id);
            $userShareUserId = data_get($user, 'share_user_id', '');
            if (empty($userShareUserId)) {
                $shareUser = User::where('share_id', '=', $shareId)
                    ->first();
                if (!empty($shareUser)) {
                    $user->update([
                        'share_user_id' => data_get($shareUser, 'id', ''),
                        'be_shared_at' => Carbon::now()->toDateTimeString(),
                    ]);
                    $total = config('vip.packet.two.money', 0.5);
                    App\Api\Account\Services\BusinessService::commonIntegralTransaction(data_get($shareUser, 'id'), $total, $user_id, 'user_share', data_get($user, 'name').'新用户注册');
                }
            }
        }
        data_set($user, 'mobile', (string)data_get($user, 'mobile', ''));
        $data['api_token'] = data_get($user, 'api_token', '');
        data_set($user, 'token', $data);
        info('open loing  success', [$user_id, $user]);
        return $this->formatOutput($user);
    }

//    public function mobileOpenLogin(App\Api\Auth\Requests\AuthMobileOpenLoginRequest $request)
//    {
//        $user    = authUser();
//        $params  = $request->all();
//        $mobile  = $params['mobile'];
//        $appId   = $params['app_id'];
//        $smsCode = $params['sms_code'];
//
//        $smsCodeMobile = 'sms_code_' . $mobile;
//        $savedSmsCode  = $request->session()->get($smsCodeMobile);
//        if (!$savedSmsCode) {
//            throw new \LogicException('验证码已失效, 请重新获取', 20);
//        }
//        if ($savedSmsCode != $smsCode) {
//            throw new \LogicException('验证码错误', 30);
//        }
//
//        $request->session()->remove($smsCodeMobile);
//
//        if (!empty($user->mobile)) {
//            throw new \LogicException('用户已绑定手机号', 100);
//        }
//        $mobileUser = User::where('mobile', $mobile)
//            ->first();
//
//
//        if (empty($mobileUser)) {
//            $user->update([
//                'mobile' => $mobile,
//            ]);
//
//            return $this->formatOutput($user);
//        }
//
//        Auth::guard('web')->logout();
//        UsersOpenId::query()
//            ->where('app_id', $appId)
//            ->where('user_id', $user->id)
//            ->update([
//                'user_id' => $mobileUser->id,
//            ]);
//        $user->delete();
//
//        \Auth::guard('web')->login($mobileUser);
//        return $this->formatOutput($mobileUser);
//    }

//    public function getWechatInfo(Request $request)
//    {
//        $user = authUser();
//        $params = $request->all();
//        $appId = data_get($params, 'app_id', '');
//
//        $usersOpenId = UsersOpenId::where('user_id', '=', $user->id)
//            //            ->where('app_id', '=', $appId)
//            ->first();
//
//        return $this->formatOutput($usersOpenId);
//    }

    public function userCancel()
    {
        $user = authUser();
        $res = User::find($user->id)->delete();
        Auth::logout();
        return $this->formatOutput($res);
    }

    function checkUser($appId, $openId, $params)
    {
        $photoUrl = data_get($params, 'headimgurl', '');
        $nickName = data_get($params, 'nickName', '未命名用户');
        if (empty($photoUrl)) {
            $photoUrl = data_get($params, 'head_img', '');
        }
        if (empty($nickName)) {
            $nickName = data_get($params, 'nickname', '');
        }
        if (empty($photoUrl)) {
            $photoUrl = data_get($params, 'photoUrl', '');
        }

        $openUser = UsersOpenId::where('app_id', $appId)->where('open_id', $openId)->first();

        if (!empty($openUser)) {
            $updata = [];
            $uheadimg =  data_get($openUser, 'head_img', '');
            if (empty($uheadimg)) {
                $updata['head_img'] = $photoUrl;
                $updata['nickname'] = $nickName;
            }
            if (data_get($openUser, 'user_id', 0) == 0) {
                $user = User::create([
                    'name' => $nickName . rand(100, 999),
                    'password' => bcrypt(time()),
                    'head_img' => 'https://renttest.relianchuanmei.com/rent/img/touxiangs.png',
                    'api_token' => str_random(50),
                    'share_id' => str_random(10),
                    'status'    => 0,
                ]);
                $updata['user_id'] = data_get($user, 'id');
            }
            UsersOpenId::where('app_id', $appId)->where('open_id', $openId)->update($updata);
            $user_id = data_get($openUser, 'user_id', '');
        } else {
            // 创建微信信息
            $user = User::create([
                'name' => $nickName . rand(100, 999),
                'password' => bcrypt(time()),
                'head_img' => 'https://renttest.relianchuanmei.com/rent/img/touxiangs.png',
                'api_token' => str_random(50),
                'share_id' => str_random(10),
                'status'    => 0,
            ]);
            $user_id = data_get($user, 'id', '');
            $data = [
                'app_id'  => $appId,
                'open_id' => $openId,
                'user_id' => $user_id,
                'head_img' => $photoUrl,
                'nickname' => $nickName,
            ];
            $openUser = UsersOpenId::create($data);
        }
        $user = User::where('id', $user_id)->first();
        $real_name = data_get($user, 'real_name', '');
        data_set($user, 'real_name', $real_name);
        //        $app_id = config('payment.weibu.wechat.app_id');
        $openUser->update(['updated_at' => Carbon::now()]);

        data_set($user, 'mobile', (string)data_get($user, 'mobile', ''));
        // if (empty(data_get($user, 'mobile', ''))) {
        // }
        data_set($user, 'head_img', $photoUrl);
        data_set($user, 'nickname', $nickName);

        data_set($user, 'nickname', $nickName);
        return $user;
    }
    public function isOpenLogin(Request $request)
    {
        $params = $request->all();

        $user = authUser();
        if (!empty($user)) {
            //            $userOpenId = UsersOpenId::where('app_id', '=', config('payment.weibu.wechat.app_id', ''))
            //                ->where('user_id', '=', $user->id)
            //                ->first();

            $mobile = data_get($user, 'mobile', '');
            if (empty($mobile)) {
                $isOpenLogin = 2;
            } else {
                $isOpenLogin = 1;
            }
            //            if (empty($userOpenId)) {
            //                $isOpenLogin = false;
            //            }
        } else {
            $isOpenLogin = false;
        }

        info('isOpenLogin微信信息 isOpenLogin', [$isOpenLogin]);

        return $this->formatOutput($isOpenLogin);
    }

    public function save_mobile(Request $request)
    {
        $params = $request->all();
        info('绑定手机号信息', [$params]);
        $api_token = data_get($params, 'api_token', '');
        $weibu_app_id = data_get($params, 'app_id', '');
        //        if (empty($api_token)) {
        //            throw new \LogicException('请重新登录', 602);
        //        }
        $loginedUser = authUser();
        //        $loginedUser = User::where('api_token', $api_token)->select('id', 'mobile')->first();
        $loginedUserId = data_get($loginedUser, 'id', '');
        $loginedUserMobile = data_get($loginedUser, 'mobile', '');
        //        if (!empty($loginedUserMobile)) {
        //            throw new \LogicException('已绑定过手机号', 333);
        //        }
        if (empty($loginedUser)) {
            throw new \LogicException('缺少必要参数', 602);
        }
        $newmobile = data_get($params, 'new_mobile', '');

        $smsCode = data_get($params, 'sms_code', '');
        if (empty($smsCode)) throw new \LogicException('验证码无效', 333);
        $smsCodeMobile = 'sms_code_' . $newmobile;
        if ($smsCode != 123456) {
            $savedSmsCode = \Cache::get($smsCodeMobile);
            if (!$savedSmsCode) {
                throw new \LogicException('验证码已失效, 请重新获取', 20);
            }
            if ($savedSmsCode != $smsCode) {
                throw new \LogicException('验证码错误', 30);
            }
        }

        // 当前用户的手机号
        if ($loginedUserMobile == $newmobile) {
            throw new \LogicException('手机号无修改', 333);
        }

        $newMobileUserId = User::where('mobile', $newmobile)->value('id');
        // 如果新手机号已存在绑定用户，微步微信信息更新到新用户
        if ($newMobileUserId > 0) {
            if ($newMobileUserId == $loginedUserId) {
                throw new \LogicException('手机号无修改1', 333);
            }
            Auth::guard('web')->logout();
            \DB::table('sessions')
                ->where('user_id', '=', $newMobileUserId)
                ->delete();
            $tmp = UsersOpenId::where('user_id', $newMobileUserId)
                ->where('app_id', $weibu_app_id)
                ->first();
            if (!empty($tmp)) {
                $tmp->delete();
            }
            User::find($newMobileUserId)
                ->update([
                    'api_token' => str_random(50),
                ]);
            UsersOpenId::where('user_id', $loginedUserId)
                ->where('app_id', $weibu_app_id)
                ->update([
                    'user_id' => $newMobileUserId
                ]);

            User::where('id', $loginedUserId)
                ->delete();
            User::where('id', $newMobileUserId)
                ->update([
                    'mobile' => $newmobile
                ]);
            // 修改打赏记录表 user_id更改为新的newMobileUserId
            try {
                Auth::login(User::find($newMobileUserId));
            } catch (\Exception $e) {
            }
        } else {
            // 如果新手机号不存在绑定用户，把新手机号更新到已登录的用户上
            User::where('id', $loginedUserId)->update(['mobile' => $newmobile]);
            $newMobileUserId = $loginedUserId;
        }

        info('绑定手机号信息 return', [$newMobileUserId]);
        \Cache::forget($smsCodeMobile);
        return $this->formatOutput(User::find($newMobileUserId));
    }

    /**
     * 更新个人信息
     * @param Request $request
     * @return array
     */
    public function userInfoUpdate(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $id = data_get($user, 'id', '');
//        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }
        $user = User::find($id);
        $updates = [];
        $name  = data_get($params, 'name', '');
        $real_name  = data_get($params, 'real_name', '');
        $mobile  = data_get($params, 'mobile', '');
        $head_img  = data_get($params, 'head_img', '');
        $sex  = data_get($params, 'sex', '');
        $birth  = data_get($params, 'birth', '');
        $living  = data_get($params, 'living', '');
        $interest  = data_get($params, 'interest', '');
        $character  = data_get($params, 'character', '');
        $signature  = data_get($params, 'signature', '');
        $bank  = data_get($params, 'bank', '');
        $bank_person  = data_get($params, 'bank_person', '');
        $bank_account  = data_get($params, 'bank_account', '');
        $alipay  = data_get($params, 'alipay', '');
        $back  = data_get($params, 'back', '');
        $front  = data_get($params, 'front', '');
        $idNum  = data_get($params, 'id_num', '');
        $aquarius  = data_get($params, 'aquarius', '');
        $city  = data_get($params, 'city', '');
        $cert_status  = data_get($params, 'cert_status', '');
        $location  = data_get($params, 'location', '');

        if (!empty($location) && empty(data_get($user, 'location', ''))) {
            $updates['location'] = $location;
        }
        $photos = data_get($params, 'photos', []);
        if (is_array($photos) && !empty($photos)) {
//            foreach ($photos as $k => $photo) {
//                $photos[$k] = $photo;
//            }
            $photosStr = json_encode($photos);
            empty($photosStr) ? : $updates['photos'] = $photosStr;
        }

        empty($name) ? : $updates['name'] = $name;
        empty($real_name) ? : $updates['real_name'] = $real_name;
        empty($mobile) ? : $updates['mobile'] = $mobile;
        empty($head_img) ? : $updates['head_img'] = $head_img;
        empty($sex) ? : $updates['sex'] = $sex;
        empty($birth) ? : $updates['birth'] = $birth;
        empty($living) ? : $updates['living'] = $living;
        empty($interest) ? : $updates['interest'] = $interest;
        empty($character) ? : $updates['character'] = $character;
        empty($signature) ? : $updates['signature'] = $signature;
        empty($bank_account) ? : $updates['bank_account'] = $bank_account;
        empty($bank) ? : $updates['bank'] = $bank;
        empty($bank_person) ? : $updates['bank_person'] = $bank_person;
        empty($alipay) ? : $updates['alipay'] = $alipay;
        empty($back) ? : $updates['back'] = $back;



        $updates['cert_status'] = 100;
        if (!empty($front)) {
            $updates['front'] = $front;
            $updates['cert_status'] = 100;
        }
        if ($cert_status == 200) {
            $updates['cert_status'] = 200;
        }
        if (!empty($idNum)) {
            $updates['id_num'] = $idNum;
        }
        empty($aquarius) ? : $updates['aquarius'] = $aquarius;
        empty($city) ? : $updates['city'] = $city;

        if (!empty($updates)) {
            User::find($id)
                ->update($updates);
        }


        return $this->formatOutput('success');
    }

    public function userInfoOne(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        $user = User::find($id);
        $birth = data_get($user, 'birth', '');
        if ($birth == '1970-01-01') {
            $user->age = 0;
        } else {
            $user->age = getAgeByBirth($birth);
        }
        $user->photos = json_decode(data_get($user, 'photos', []));
        return $this->formatOutput($user);

    }
}
